import { observable, action, computed, runInAction } from 'mobx';

import BaseStore from '../BaseStore';
import validationUtil from '@/utils/validation';
import { noticeMessage } from '@utils/common-message';

class SignupStore extends BaseStore {
    @observable username;
    @observable password;
    @observable repeatPassword;
    @observable smsCode;
    @observable smsCodeTimeout = 0;
    @observable captcha;
    @observable captchaUrl = '';
    @observable isCaptchaModalOpen = false;
    @observable isAgreementModalOpen = false;
    @observable isAgreeAgreement = false;
    @observable errMsg = {
        username: '',
        password: '',
        repeatPassword: '',
        smsCode: '',
        captcha: ''
    };
    // 弹框提示的错误
    globalErrMsg = '';
    
    isSignupSuccess = false;
    isSendSmsCodeSuccess = false;

    @computed
    get isSubmitBtnDisabled() {
        return !this.username || 
            !this.password || 
            !this.repeatPassword ||
            !this.smsCode || 
            !this.isAgreeAgreement || 
            !validationUtil.isSMSCode(this.smsCode);
    }

    @computed
    get isSmsCodeBtnDisabled() {
        return !this.username || 
            this.smsCodeTimeout > 0;
    }
    
    @computed
    get isSendSmsCodeBtnDisabled() {
        return !this.username || 
        !this.captcha || 
        !validationUtil.isCaptcha(this.captcha); 
    }

    @action
    reset() {
        this.username = '';
        this.password = '';
        this.repeatPassword = '';
        this.smsCode = '';
        this.smsCodeTimeout = 0;
        this.captcha = '';
        this.captchaUrl = '';
        this.isCaptchaModalOpen = false;
        this.isAgreementModalOpen = false;
        this.isAgreeAgreement = false;
        this.isSignupSuccess = false;
        this.isSendSmsCodeSuccess = false;
        this.globalErrMsg = '';
        this.errMsg = {
            username: '',
            password: '',
            repeatPassword: '',
            smsCode: '',
            captcha: ''
        };
    }

    /**
     * 打开图形验证码弹框
     */
    @action
    openCaptchaModal() {
        if (!this.validateUsername()) {
            return;
        }
        this.errMsg.captcha = '';
        this.refreshCaptcha();
        this.isCaptchaModalOpen = true;
    }

    /**
     * 关闭图形验证码弹框
     */
    @action
    closeCaptchaModal() {
        this.isCaptchaModalOpen = false;
    }

    @action
    openAgreementModal() {
        this.isAgreementModalOpen = true;
    }

    @action
    closeAgreementModal() {
        this.isAgreementModalOpen = false;
    }

    /**
     * 刷新图形验证码
     */
    @action
    refreshCaptcha() {
        this.captcha = '';
        this.captchaUrl = `/captcha?type=1&${Date.now()}`;
    }

    /**
     * 验证用户名
     */
    @action
    validateUsername() {
        if (!validationUtil.isMobile(this.username)) {
            this.errMsg.username = noticeMessage.inputFormatError('手机号');
            return false;
        }
        this.errMsg.username = '';
        return true;
    }

    /**
     * 验证密码
     */
    @action
    validatePassword() {
        if (!validationUtil.isSimplePassword(this.password)) {
            this.errMsg.password = noticeMessage.passwordFormatError();
            return false;
        }
        this.errMsg.password = '';
        return true;
    }

    /**
     * 验证确认密码
     */
    @action
    validateRepeatPassword() {
        if (this.repeatPassword !== this.password) {
            this.errMsg.repeatPassword = noticeMessage.repeatPasswordError();
            return false;
        }
        this.errMsg.repeatPassword = '';
        return true;
    }

    /**
     * 验证短信验证码
     */
    @action
    validateSmsCode() {
        if (!validationUtil.isSMSCode(this.smsCode)) {
            this.errMsg.smsCode = noticeMessage.inputFormatError('短信验证码');
            return false;
        }
        this.errMsg.smsCode = '';
        return true;
    }

    /**
     * 验证图形验证码
     */
    @action
    validateCaptcha() {
        if (!validationUtil.isCaptcha(this.captcha)) {
            this.errMsg.captcha = noticeMessage.inputFormatError('图片验证码');
            return false;
        }
        this.errMsg.captcha = '';
        return true;
    }

    /**
     * 发起发送短信验证码请求
     */
    @action
    async sendSmsCode() {
        this.globalErrMsg = '';
        this.isSendSmsCodeSuccess = false;
        if (!this.validateCaptcha()) {
            return;
        }
        const res = await this.post('/sms-code', {
            mobile: this.username,
            captcha: this.captcha,
            type: 1,
        }, {
            showGlobalLoading: true,
        });
        runInAction(() => {
            const code = res.code;
            if (code === '0000') {
                this.closeCaptchaModal();
                this.isSendSmsCodeSuccess = true;
                this.smsCodeTimeout = 60;
                this.smsCodeTimer = setInterval(this.updateSmsCodeTimeout.bind(this), 1000);
            } else if (code === '1101') {
                this.closeCaptchaModal();
                this.errMsg.username = noticeMessage.inputFormatError('手机号');
            } else if (code === '1102') {
                this.errMsg.captcha = noticeMessage.inputFormatError('图片验证码');
                this.refreshCaptcha();
            } else if (code === '1201') {
                this.closeCaptchaModal();
                this.globalErrMsg = noticeMessage.requestSmsCodeTooFast();
            } else if (code === '1202') {
                this.closeCaptchaModal();
                this.globalErrMsg = noticeMessage.requestSmsCodeTooMany();
            } else if (code === '1203') {
                this.closeCaptchaModal();
                this.errMsg.username = '该用户已注册，请前往登录';
            } else {
                this.closeCaptchaModal();
                this.globalErrMsg = res.message || '获取短信验证码失败';
            }
        });
    }

    @action
    updateSmsCodeTimeout() {
        runInAction(() => {
            if (this.smsCodeTimeout > 0) {
                this.smsCodeTimeout--;
                return;
            }
            clearInterval(this.smsCodeTimer);
        });
    }

    /**
     * 发起注册请求
     */
    @action
    async signup() {
        this.globalErrMsg = '';
        if (!this.validateUsername() || !this.validatePassword() || !this.validateRepeatPassword() || !this.validateSmsCode()) {
            return;
        }
        const res = await this.post('/user/signup', {
            username: this.username,
            password: this.password,
            repeat_password: this.repeatPassword,
            mobile_verify_code: this.smsCode,
        }, {
            showGlobalLoading: true,
        });
        const code = res.code;
        runInAction(() => {
            if (code === '0000') {
                this.isSignupSuccess = true;
            } else if (code === '1200') {
                this.errMsg.username = '该用户已注册，请前往登录';
            } else if (code === '1201') {
                this.errMsg.smsCode = noticeMessage.smsCodeError();
            } else if (code === '1202') {
                this.errMsg.smsCode = noticeMessage.smsCodeExpire();
            } else {
                this.globalErrMsg = res.message || '注册失败,请重试';
            }
        });   
    }
}

export default new SignupStore();
